import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHash } from 'crypto';
import { Conflux, PrivateKeyAccount } from 'js-conflux-sdk';

@Injectable()
export class ConfluxService {
  private readonly client: Conflux;
  private readonly networkId: number;
  private readonly address: string;
  private readonly privateKey: string;

  constructor(private readonly config: ConfigService) {
    this.networkId = this.config.get('conflux.networkId');
    this.address = this.config.get('conflux.address');
    this.privateKey = this.config.get('conflux.privateKey');
    this.client = new Conflux({
      url: this.config.get('conflux.url'),
      networkId: this.networkId,
    });
  }

  async createAccount(id: string): Promise<any> {
    return new Promise((r) => {
      r(
        PrivateKeyAccount.random(
          '0x' + createHash('sha256').update(id).digest('hex'),
          this.networkId,
        ),
      );
    });
  }

  async getBalance(address: string) {
    return await this.client.cfx.getBalance(address);
  }
}
